import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';

import '../text_util.dart';

/// @author: pengboboer
/// @createDate: 2021/11/11
/// 目前用到这么多属性，先这样，后续有特殊需要再加
/// 兼容空url、网络图片、本地文件
class DefaultNetworkImage extends StatelessWidget {
  final String? url;
  final double? width;
  final double? height;
  final Widget? errorWidget;
  final BoxFit? boxFit;

  const DefaultNetworkImage(this.url,
      {Key? key, this.width, this.height, this.errorWidget, this.boxFit})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (TextUtil.isEmpty(url)) {
      return SizedBox(
        width: width,
        height: height,
        child: errorWidget ??
            Container(
              color: const Color(0xfff2f2f2),
            ),
      );
    }

    if (url!.startsWith("http")) {
      return CachedNetworkImage(
        imageUrl: url!,
        width: width,
        height: height,
        fit: boxFit ?? BoxFit.cover,
        fadeInDuration: const Duration(milliseconds: 250),
        fadeOutDuration: const Duration(milliseconds: 0),
        errorWidget: (context, url, error) =>
            errorWidget ??
            Container(
              color: const Color(0xfff2f2f2),
            ),
        // placeholder: (context, index) => Image.asset(
        //   'images/icon_greens_logo.png',
        //   fit: BoxFit.cover,
        // ),
        placeholder: (context, index) => Container(
          color: const Color(0xfff2f2f2),
        ),
      );
    }

    return Image.file(
      File(url!),
      width: width,
      height: height,
      fit: boxFit ?? BoxFit.cover,
      errorBuilder:
          (BuildContext context, Object error, StackTrace? stackTrace) {
        return Container(
          color: const Color(0xfff2f2f2),
        );
      },
    );
  }
}
